package bugzillapreprocessor.parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import bugzillapreprocessor.model.Issue;

/**
 * The Parser class is a wrapper around Java's SAX parser, customized for this
 * package.
 * 
 * @author c_haras
 */
public class Parser {

	private SAXParser saxParser;
	private XMLParseHandler handler;

	/**
	 * Constructor
	 */
	public Parser() {
		SAXParserFactory factory = SAXParserFactory.newInstance();

		try {
			saxParser = factory.newSAXParser();
			handler = new XMLParseHandler();
		} catch (ParserConfigurationException ex) {
			Logger.getLogger(Parser.class.getName())
					.log(Level.SEVERE, null, ex);
		} catch (SAXException ex) {
			Logger.getLogger(Parser.class.getName())
					.log(Level.SEVERE, null, ex);
		}
	}

	/**
	 * Assign the SAX parser to the XML file
	 * 
	 * @param filename
	 *            The name of the XML file to parse
	 */
	public void parse(String filename) {
		try {
			saxParser.parse(filename, handler);
		} catch (SAXException ex) {
			Logger.getLogger(Parser.class.getName())
					.log(Level.SEVERE, null, ex);
		} catch (IOException ex) {
			Logger.getLogger(Parser.class.getName())
					.log(Level.SEVERE, null, ex);
		}
	}

	/**
	 * Produce a list of issue objects based on the parsed XML file
	 * 
	 * @return A list if issue objects
	 */
	public ArrayList<Issue> getIssues() {
		return handler.getIssueList();
	}
}
